<?php

namespace App\Http\Controllers\H5;

use App\Common\Utils\EasyWechat;
use App\Events\AgentLogin;
use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Services\Authorization;
use App\Services\Captcha;
use Carbon\Carbon;
use Dingo\Api\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Psr\Http\Message\ResponseInterface;

class AuthController extends Controller
{
    public function store(Request $request)
    {
        if ($request->has('debug') && $request->get('debug_pwd') === md5(env('APP_DEBUG_PWD'))) {
            $token = Auth::guard('h5')->tokenById($request->get('debug_agent_id'));
            return $this->response->created(null, (new Authorization($token))->toArray());
        }

        if (!$token = Auth::guard('h5')->attempt(
            Arr::add($request->only(['phone', 'password']), 'status', Agent::STATUS_NORMAL)
        )) {

            $this->response->errorBadRequest(trans('auth.incorrect'));
        }

        try {
            $auth = Auth::guard('h5');
            event(new AgentLogin($auth->id())); // 收信等等
            Redis::hset(sprintf('index_daily_statistics:%s:number_of_level_%s_active_agent', Carbon::today()->format('Ymd'), $auth->user()->level), $auth->id(), 1); // 统计 uv
        } catch (\Exception $e) {
            \Log::error(sprintf('用户登录出现异常: %s (%s [%s])', $e->getMessage(), $e->getFile(), $e->getLine()));
        }

        return $this->response->created(null, (new Authorization($token))->toArray());
    }

    /**
     * 微信小程序登录
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function storeByWechatMini(Request $request)
    {
        $app = EasyWechat::getMiniProgram();
        $session = $app->auth->session($request->get('code', ''));
        $decryptedData = $app->encryptor->decryptData(
            $session['session_key'] ?? '',
            $request->get('iv', ''),
            $request->get('encryptedData', '')
        );
        \Log::info('$decryptedData: ' . json_encode($decryptedData));
        try {
            $token = Auth::guard('h5')->tokenById(
                Agent::query()->where('phone', $decryptedData['purePhoneNumber'] ?? '')->firstOrFail('id')->id
            );
        } catch (ModelNotFoundException $e) {
            $this->response->errorBadRequest('该微信用户没有注册,请先注册');
        }
        return $this->response->created(null, (new Authorization($token))->toArray());
    }

    /**
     * 微信小程序码
     * @param Request $request
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    public function getMiniAppCodeUnlimit(Request $request)
    {
        $app = EasyWechat::getMiniProgram();
        $appCodeRes = $app->app_code->getUnlimit($request->get('scene', ''), $request->only(['page', 'width', 'auto_color', 'line_color', 'is_hyaline']));
        if ($appCodeRes instanceof ResponseInterface && $appCodeRes->getStatusCode() !== 200) {
            $this->response->error(json_decode($appCodeRes->getBody()->getContents(), true), $appCodeRes->getStatusCode());
        }
        return $appCodeRes;
    }

    public function update()
    {

        return $this->response->created(null, (new Authorization(Auth::refresh()))->toArray());
    }

    public function destory()
    {
        Auth::logout();

        return $this->response->noContent();
    }

    public function resetPassword(Request $request)
    {
        if (!Captcha::verificationSmsCaptcha($request)) {
            $this->response->errorBadRequest('短信验证码错误或者已过期');
        }

        Agent::query()
            ->where('phone', $request->phone)
            ->update(['password' => Hash::make($request->password)]);

        return $this->response->created();
    }

    public function resetPasswordByOldPwd(Request $request)
    {
        // 验证提交的旧密码
        if (!$token = Auth::attempt([
            'phone' => Auth::user()->phone,
            'password' => $request->get('old_password'),
            'status' => Agent::STATUS_NORMAL
        ], false)) {
            $this->response->errorBadRequest('旧密码错误');
        }
        // 修改新密码
        $newPwd = $request->get('password');
        $confirmPwd = $request->get('confirm_password');
        if ($newPwd !== $confirmPwd) {
            $this->response->errorBadRequest('输入的两次密码不一致');
        }

        Auth::user()->update(['password' => Hash::make($newPwd)]);

        Auth::logout();

        return $this->response->noContent();
    }
}
